package com.siruier.boss.ui.activity.mall

import android.view.View
import androidx.activity.viewModels
import com.siruier.boss.R
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.mallApi
import com.siruier.boss.bean.ConfirmOrderGoodsBean
import com.siruier.boss.bean.GoodsOrderShowStateEnum
import com.siruier.boss.bean.GoodsOrderStateEnum
import com.siruier.boss.bean.OrderDetailBean
import com.siruier.boss.common.ADDividerItemDecoration
import com.siruier.boss.common.buildPrice
import com.siruier.boss.common.orderType
import com.siruier.boss.common.toArray
import com.siruier.boss.databinding.ActivityUserOrderCenterBinding
import com.siruier.boss.databinding.ItemUserOrderCenterBinding
import com.siruier.boss.databinding.ItemUserOrderCenterGoodsBinding
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.base.BaseRecyclerAdapter
import com.siruier.boss.ui.ext.textSpan
import com.siruier.boss.ui.helper.InjectBundle
import com.siruier.boss.ui.helper.RefreshHelper
import com.siruier.boss.ui.listener.OnTabSelectedListener
import com.siruier.boss.ui.utils.FullyLinearLayoutManager
import com.siruier.boss.ui.utils.GlideUtils
import com.siruier.boss.ui.viewmodel.OrderViewModel

class UserOrderCenterActivity : BaseActivity<ActivityUserOrderCenterBinding>() {
    companion object {
        private val mGoodsOrderStateEnum: Array<GoodsOrderShowStateEnum> = GoodsOrderShowStateEnum.values()
        val mOrderShowStateMap: MutableMap<Int, String> = mutableMapOf()

        init {
            GoodsOrderStateEnum.values().forEach {
                mOrderShowStateMap[it.state] = it.stateShow
            }
        }
    }

    private val mOrderViewModel: OrderViewModel by viewModels()
    private val mOrderState: Int by InjectBundle { GoodsOrderShowStateEnum.ALL.state }

    private lateinit var mRefreshHelper: RefreshHelper<OrderDetailBean>
    private val mUserOrderAdapter = UserOrderAdapter()

    override fun initView() {
        mRefreshHelper = RefreshHelper(vb.refreshLayout, vb.recyclerView, mUserOrderAdapter) { onReload() }
        var tabIndex = 0
        mGoodsOrderStateEnum.forEachIndexed { index, orderState ->
            vb.tabLayout.addTab(vb.tabLayout.newTab().setText(orderState.stateName))
            if (mOrderState == orderState.state) {
                tabIndex = index
            }
        }
        vb.tabLayout.getTabAt(tabIndex)?.select()
        vb.tabLayout.addOnTabSelectedListener(OnTabSelectedListener { mRefreshHelper.onRefresh() })
        vb.recyclerView.addItemDecoration(ADDividerItemDecoration(this, R.drawable.linear_layout_line_8))
        mUserOrderAdapter.setOnClickAdapterListenter { view, i ->
            mOrderViewModel.handOrderClick(this, mUserOrderAdapter.getItem(i), view.id)
        }
        mOrderViewModel.handSuccess.observe(this) {
            onReload()
        }
        mRefreshHelper.onRefresh()
    }

    private fun onReload() {
        launchUI({
            mallApi.orderList(mGoodsOrderStateEnum[vb.tabLayout.selectedTabPosition].state, mRefreshHelper.page).toData()?.records
        }, mRefreshHelper.handApiObserver())
    }

    private fun openUserOrderDetails(orderSn: String) {
        launchStartActivityForResult(UserOrderDetailsActivity::class.java, options = {
            putString("mOrderSn", orderSn)
        }) {
            onReload()
        }
    }


    inner class UserOrderAdapter : BaseRecyclerAdapter<ItemUserOrderCenterBinding, OrderDetailBean>() {

        override fun onBindViewHolder(vb: ItemUserOrderCenterBinding, bean: OrderDetailBean, position: Int) {
            vb.apply {
                bean.apply {
                    tvShopName.text = orderType
                    tvOrderStatus.text = mOrderShowStateMap[orderStatus] ?: "未知"
                    // 目前是单个商品购买直接去的哥商品数据，后期购物车需要修改
                    tvPriceNote.textSpan("共${goodsList[0].number}件 合计：￥${buildPrice(orderPrice)}") {
                        spanText = buildPrice(orderPrice)
                        addBoldSpan()
                    }
                    var adapter = rvUserOrder.adapter as? ShoppingCartGoodsAdapter
                    if (adapter == null) {
                        adapter = ShoppingCartGoodsAdapter()
                        rvUserOrder.adapter = adapter
                        rvUserOrder.layoutManager = FullyLinearLayoutManager(rvUserOrder.context)
                    }
                    adapter.mOrderDetailBean = this
                    adapter.datas = goodsList
                    adapter.notifyDataSetChanged()
                    setViewClick(position, rootView, textOrderButtonPay, textOrderButtonCancel)
                }
            }
        }

        override fun subOnClickAdapter(v: View, position: Int) {
            val goodsOrderBean = getItem(position)
            when (v.id) {
                //R.id.tvShopName -> ShopDetailsActivity.openMall(goodsOrderBean.storeId, this@UserOrderCenterActivity)
                R.id.rootView -> openUserOrderDetails(goodsOrderBean.orderSn)
            }
        }
    }

    inner class ShoppingCartGoodsAdapter : BaseRecyclerAdapter<ItemUserOrderCenterGoodsBinding, ConfirmOrderGoodsBean>() {
        var mOrderDetailBean: OrderDetailBean? = null

        override fun onBindViewHolder(vb: ItemUserOrderCenterGoodsBinding, bean: ConfirmOrderGoodsBean, position: Int) {
            vb.run {
                bean.apply {
                    GlideUtils.intoRoundedCorners(ivShopHead.context, picUrl, ivShopHead, roundingRadius = 5)
                    tvGoodsName.text = goodsName
                    tvSpec.text = getString(R.string.text_shopping_cart_spec, specifications.toArray(String::class.java).joinToString(" "))
                    mOrderDetailBean?.apply { tvSpecPrice.text = getString(R.string.text_pay_fee_rmb, buildPrice(price)) }
                    tvNumber.text = "x$number"
                    setViewClick(position, root)
                }
            }
        }

        override fun subOnClickAdapter(v: View, position: Int) {
            mOrderDetailBean?.let { openUserOrderDetails(it.orderSn) }
        }
    }
}

//        viewPager.adapter = UserOrderTabAdapter(this, fragments)
//        viewPager.offscreenPageLimit = fragments.size
//        TabLayoutMediator(tabLayout, viewPager) { tab, position -> tab.text = tabText[position] }.attach()
//    class UserOrderTabAdapter(fragmentActivity: FragmentActivity, var fragments: MutableList<Fragment>) : FragmentStateAdapter(fragmentActivity) {
//        override fun getItemCount() = fragments.size
//        override fun createFragment(position: Int) = fragments[position]
//    }